package com.sys.app.entity.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sys.app.entity.sys.SysAccount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.UUID;

public class TokenUtil {
    private static Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    //签发者
    private static final String tokenIssuer="f12";
    //token到期时间1小时：1000*60*60
    private static final long EXPIRE_TIME= 1000*60*60;
    //密钥盐
    private static final String TOKEN_SECRET="OWb641r4Fg87e80DWf34g56vs3N8it";

    /**
     * 创建一个token
     * @param user
     * @return
     */
    public static String sign(SysAccount user){
        /*
          Claims claims = Jwts.claims();
        *  claims.setIssuer(username); // jwt发行人
        claims.setIssuedAt(new Date()); // jwt生成时间
        claims.setExpiration(getExp()); // jwt过期时间
        claims.setSubject("auth"); // jwt主题
        claims.setAudience("yhc"); // jwt接受方
        claims.setId("uuid"); // jwt唯一身份标识
        claims.setNotBefore(new Date()); // jwt在此之前不可用
        * */
        String token=null;
        try {
            Date expireAt=new Date(System.currentTimeMillis()+EXPIRE_TIME);
            token = JWT.create()
                    //发行人
                    .withIssuer(tokenIssuer)
                    //过期时间
                    .withExpiresAt(expireAt)
                    //存放数据
                    .withClaim("id",user.getId())
                    .withClaim("userCode",user.getCode())
                    .withClaim("userName",user.getName())
                    //加密
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException| JWTCreationException je) {
            logger.error(je.toString());
        }
        //logger.info(String.format("[%s]==token==:%s",user.getCode(),token));
        return token;
    }
    /**
     * 对token进行验证
     * @param token
     * @return
     */
    public static Boolean verify(String token){
        try {
            //创建token验证器
            JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer(tokenIssuer).build();
            DecodedJWT decodedJWT=jwtVerifier.verify(token);
            logger.info(String.format("认证通过:%s,过期时间:%s",TokenUtil.getUserInfo(token).getCode(),decodedJWT.getExpiresAt()));
        } catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            logger.error(e.toString());
            return false;
        }
        return true;
    }

    /**
     * 获取jwt过期时间
     * @param token
     * @return
     */
    public static Long getJwtExpiresAt(String token) {
        try {
            //创建token验证器
            JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer(tokenIssuer).build();
            DecodedJWT decodedJWT=jwtVerifier.verify(token);
            return decodedJWT.getExpiresAt().getTime();
        } catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            logger.error(e.toString());
            return new Date().getTime();
        }
    }

    /**
     * 获取用户名
     */
    public static SysAccount getUserInfo(String token){
        try{
            SysAccount user=new SysAccount();
            DecodedJWT jwt= JWT.decode(token);
            user.setId(jwt.getClaim("id").asLong());
            user.setCode(jwt.getClaim("userCode").asString());
            user.setName(jwt.getClaim("userName").asString());
            return user;
        }catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }
}
